package com.hxzy.common.util;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.IoUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * 获取Servlet(Spring方式)
 */
public class ServletUtil {

    public static HttpServletRequest getRequest(){

        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }


    /**
     * 向前端输出json数据
     * @param response
     * @param jsonValue
     */
    public static void renderString(HttpServletResponse response,String jsonValue){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Writer writer = null;
        try {
            writer = response.getWriter();
            writer.write(jsonValue);
            writer.flush();
        } catch (IOException e) {
            throw new UtilException(e);
        } finally {
            IoUtil.close(writer);
        }
    }

}
